<template>
  <div id="space-show" v-if="Object.keys(currentSpace).length" :class="pageWithSidebar">
    <SpaceSidebar/>
<!--    <HeaderReminder/>-->
    <router-view/>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import HeaderReminder from '@/components/announcement/HeaderReminder';
import SpaceSidebar from './SpaceSidebar';
import * as format from './format';

export default {
  name: 'SpaceShow', // 路由指向的空间展示界面
  components: { HeaderReminder, SpaceSidebar },
  data() {
    return {
      isLoading: false, // 正在加载侧边栏数据
    };
  },
  computed: {
    ...mapState(['currentSpace', 'sidebarCollapsed', 'invisibleSidebar']),
    // 有侧边栏的页面调用这个方法生成样式
    pageWithSidebar() {
      let className = 'page-with-sidebar';
      if (window.innerWidth < 1200 || this.sidebarCollapsed) className += ' sidebar-collapsed';
      if (window.innerWidth < 768 || this.invisibleSidebar) className += ' invisible-sidebar';
      return className;
    },
    // 空间id
    spaceId() { return this.$route.params.spaceId; },
    // 加入空间的key
    joinKey() { return this.$route.query.key; },
  },
  methods: {
    ...mapActions(['setCurrentSpace', 'setCurrentSpaceSidebarStatistics', 'removeCurrentSpace']),
    // 加载空间数据
    loadSpace() {
      this.$api.spaces.show({ spaceId: this.spaceId })
        .then((res) => {
          this.setCurrentSpace(format.formatSpace(res.data));
          this.loadSidebarItemsCount(); // 后加载侧边栏数据
        })
        .catch((err) => { if (err) this.goBack(); });
    },
    // 加入空间
    joinSpace() {
      this.$api.spaces.join({ joinKey: this.joinKey })
        .then((res) => {
          this.$message.success('加入成功');
          this.$root.$emit('routerPush', { path: `/${this.$rp.SPACES}/${res.data.id}` });
        })
        .catch((err) => { if (err) this.goBack(); });
    },
    // 加载侧边栏资源区、讨论区等个数统计
    loadSidebarItemsCount() {
      if (this.isLoading) return;
      this.isLoading = true;
      this.$api.spaces.asideCount({ spaceId: this.spaceId })
        .then((res) => {
          this.setCurrentSpaceSidebarStatistics(format.formatSpaceSidebarStatistics(res.data));
        })
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
  },
  created() {
    if (!this.spaceId && this.joinKey) this.joinSpace();
    else {
      this.loadSpace();
      this.$root.$on('loadSidebarItemsCount', this.loadSidebarItemsCount);
    }
  },
  destroyed() {
    this.removeCurrentSpace();
  },
  watch: {
    // 监听当前路由的空间id，切换时重新加载空间数据
    spaceId() {
      this.removeCurrentSpace();
      this.loadSpace();
    },
    // 监听当前路由，如果是返回首页，就刷新空间数据
    $route(val) {
      if ([undefined, 'homepage'].includes(val.path.split('/')[3])) this.loadSpace();
    },
  },
};
</script>

<style></style>
